package com.tinem.platform.module.commons.util;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className NumberUtil
 * @description 数字压缩，从10进制压缩为62进制
 * @site
 * @company
 * @create 2021/12/24 12:48:22
 */
public class NumberUtil {
    static char[] HEXADECIMAL_DIGIT = new char[]{
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
            , 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H','I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
            , 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h','i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
    };
    final static Map<Character, Integer> digitMap = new HashMap<Character, Integer>(){{
        for (int i = 0; i < HEXADECIMAL_DIGIT.length; i++) {
            put(Character.valueOf(HEXADECIMAL_DIGIT[i]), Integer.valueOf(i));
        }
    }};

    public static String zipNumber(Long number){
        StringBuilder sb = new StringBuilder();
        while (number != 0) {
            sb.append(HEXADECIMAL_DIGIT[(int) (number%HEXADECIMAL_DIGIT.length)]);
            number = number / HEXADECIMAL_DIGIT.length;
        }
        String s = sb.reverse().toString();
        return s;
    }
    public static Long unZipNumber(String number){
        // 返回结果
        long result = 0;
        char[] ss = number.toCharArray();
        // 计算阶乘
        long factorial = 1;
        for (int i = (ss.length - 1); i >= 0; i--) {
            char c = ss[i];
            Integer v = digitMap.get(Character.valueOf(c));
            if (v != null) {
                result += v.intValue() * factorial;
                factorial *= HEXADECIMAL_DIGIT.length;
            }
        }
        return result;
    }
}
